package com.zhongyu.controller;

import lombok.SneakyThrows;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import org.apache.ibatis.io.Resources;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("sys/user")
public class UserReportController {
    @Resource
    private DataSource dataSource;
    /**
     * 导出Excel
     */
    @SneakyThrows
    @GetMapping("/exportExcel")
    public void  exportEcel(HttpServletResponse response){
        InputStream inputStream= Resources.getResourceAsStream("jasper/userReport.jasper");
       Connection conn= dataSource.getConnection();
        JasperPrint jasperPrint= JasperFillManager.fillReport(inputStream,null,conn);
String title="userReport";

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition","attachment;filename="
+title+".xlsx");
//final OutputStream outputStream=response.getOutputStream();
     //   JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);


        JRXlsxExporter exporter = new JRXlsxExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        exporter.exportReport();
    }
    @SneakyThrows
    @GetMapping("/exportPdf")
    public void exportpdf(HttpServletResponse response) {


        ServletOutputStream servletOutputStream = response.getOutputStream();
     //   System.out.println("输出来自页面携带的参数：" + id);
        InputStream inputStream = Resources.getResourceAsStream("jasper/userReport.jasper");
        Connection conn = dataSource.getConnection();
        Map parameters = new HashMap<>();
     //   parameters.put("cid", id);

        JasperRunManager.runReportToPdfStream(inputStream, servletOutputStream, null, conn);
        response.setContentType("application/pdf");

        String title="userReport";
        response.setHeader("Content-Disposition", "attachment;filename=" + title + ".xlsx");
        servletOutputStream.flush();
        servletOutputStream.close();
    }

}
